<template>
  <div>
    <!--      面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--      卡片识图-->
    <el-card>

      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!--      权限列表区-->
<!--      row-key在使用 reserve-selection 功能与显示树形数据时，该属性是必填的。-->
      <el-table :data="roleList" border stripe row-key="id">
        <!--          索引列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
<!--              渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--              渲染二级权限和三级权限-->
              <el-col :span="19">
                <el-row class="vcenter" v-for="(item2,i2) in item1.children" :key="i2">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
<!--                  渲染三级权限-->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="i3" closable @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="180px">
          <!--            作用域插槽-->
          <template slot-scope="scope">
            <!--             修改按钮-->
            <!--              open-delay延迟出现，单位毫秒 enterable 鼠标是否可进入到 tooltip 中-->
            <el-tooltip effect="dark" content="修改用户" placement="top" :open-delay=openDelay :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
            </el-tooltip>
            <!--              删除按钮-->
            <el-tooltip effect="dark" content="删除用户" placement="top" :open-delay=openDelay :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini"></el-button>
            </el-tooltip>
            <!--              分配权限按钮-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :open-delay=openDelay :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--      分配权限弹框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightDialogClose">
<!--      树形控件-->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight()">确 定</el-button>
    </span>
    </el-dialog>

  </div>
</template>

<style scoped>
</style>

<script>
export default {
  data () {
    return {
      // 角色列表
      roleList: [],
      // 权限列表
      rightsList: [],
      openDelay: 500,
      // 分配权限开关
      setRightsDialogVisible: false,
      // 当前角色id
      roleId: '',
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的树形节点id数组
      defKeys: []
    }
  },
  methods: {
    //  获取所有角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },
    // 删除弹框
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      //  取消删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }
      //  确认删除
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      role.children = res.data
    },
    //  展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限树状数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data

      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)

      this.setRightsDialogVisible = true
    },
    // 递归获取到所有角色下三级权限的id
    getLeafKeys(node, arr) {
      // 如果当前节点不包含children属性，则为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听关闭分配权限对话框的事件
    setRightDialogClose() {
      this.defKeys = []
    },
    //  提交角色修改权限表单
    async setRight(role) {
      // ...展开运算符
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      //  拼接成字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 刷新列表
      this.getRoleList()
      //  关闭对话框
      this.setRightsDialogVisible = false
    }
  },
  created () {
    //  获取所有权限列表
    this.getRoleList()
  }
}
</script>
